import { createStyles } from 'antd-style';
import { ConfigContext } from 'antd/es/config-provider/context';
import { useContext, useEffect, useMemo, useRef, useState } from 'react';

const useStyle = createStyles(({ prefixCls }) => {
  return {
    rewrite: {
      [`.${prefixCls}-spin-nested-loading`]: {
        height: '100%',
        [`.${prefixCls}-spin-container`]: {
          height: '100%',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'stretch', //均匀分布
          [`.${prefixCls}-table`]: {
            flexGrow: 1, //自动撑开到父级高度
            // height: 1,
            display: 'flex',
            flexDirection: 'column',
            [`.${prefixCls}-table-container`]: {
              flexGrow: 1,
              // height: 1,
              [`.${prefixCls}-table-content`]: {
                height: '100%',
              },
            },
          },
        },
      },
      [`.${prefixCls}-table-content  table:has(.${prefixCls}-table-placeholder)`]:
        {
          minHeight: '100%',
        },
      [`.${prefixCls}-table-empty .${prefixCls}-table-body table`]: {
        minHeight: '100%',
      },
    },
  };
});

function getRectHeightContainMargin(dom: HTMLElement) {
  const style = window.getComputedStyle(dom);
  return (
    dom.clientHeight +
    parseFloat(style.marginTop) +
    parseFloat(style.marginBottom)
  );
}

/**
 * @desc 让antdtable始终充满空间的hooks,使用之后就用户无法设置scrollY属性
 */
export function useAntdTableScrollY(
  filterHeight: number,
  tableExpendKeys: readonly React.Key[],
  dataSourceLenght?: number,
) {
  const { getPrefixCls } = useContext(ConfigContext);
  const prefixCls = useMemo(() => {
    return getPrefixCls();
  }, [getPrefixCls]);

  // 内部用来控制滚动高度用的,不允许用户设置
  const [scrollY, setScrollY] = useState<number>();
  // 表格的ref dom
  const tableRef = useRef<HTMLDivElement>(null);
  const tableWrapperHeight = tableRef.current?.clientHeight;
  // const firstChild = tableRef.current?.getElementsByClassName('ant-table-tbody')
  const firstChild = tableRef.current?.childNodes[0] as HTMLDivElement;
  // console.log('--tableRef.current--:', tableRef.current);
  // 当table设置了scrollY时：table dom 结构是 <div class="ant-table-container"> <div class="ant-table-header"><table/></div>  <div class="ant-table-body"><table/></div> </div>
  // scrollY === undefined时：table dom结构是  <div class="ant-table-content"> <table><thead class="antd-table-thead" /><tbody class="antd-table-tbody" /></table> </div>

  // 计算表格body区域的实际高度
  useEffect(() => {
    let otherH = 0;

    // 分页dom
    const pagination = firstChild?.getElementsByClassName(
      `${prefixCls}-table-pagination`,
    )?.[0] as HTMLDivElement | undefined;
    // 表头的外层dom
    const headerDom = firstChild?.getElementsByClassName(
      `${prefixCls}-table-thead`,
    )[0] as HTMLDivElement | undefined;
    // 用户通过footer传递给表格的地步插入元素
    const tableFooter = firstChild?.getElementsByClassName(
      `${prefixCls}-table-footer`,
    )[0] as HTMLDivElement | undefined;

    if (headerDom) {
      otherH += getRectHeightContainMargin(headerDom);
    }
    if (pagination) {
      otherH += getRectHeightContainMargin(pagination);
    }
    if (tableFooter) {
      otherH += getRectHeightContainMargin(tableFooter);
    }
    if (tableWrapperHeight && dataSourceLenght) {
      const tableDom = firstChild?.getElementsByClassName(
        `${prefixCls}-table`,
      )[0] as HTMLDivElement | undefined;
      const tbodyDom = tableDom?.getElementsByClassName(
        //<div class="ant-table-body">
        `${prefixCls}-table-body`,
      )[0] as HTMLDivElement | undefined;

      const tableContentDom = firstChild?.getElementsByClassName(
        `${prefixCls}-table-content`,
      )[0] as HTMLDivElement | undefined;
      // console.log('--tableWrapperHeight , otherH--:',tableWrapperHeight , otherH);

      if (tableContentDom) {
        const tableContentHeight = getRectHeightContainMargin(tableContentDom);
        // console.log('--tableContentHeight--:', tableContentHeight);
        const contentHeightExculeHeader =
          tableContentHeight -
          (headerDom ? getRectHeightContainMargin(headerDom) : 0);
        // 判断是否需要滚动条
        if (
          tableContentHeight &&
          tableWrapperHeight - otherH > contentHeightExculeHeader
        ) {
          // console.log('---tableContentDom--不需要滚动条--');
          setScrollY(undefined);
        } else {
          // console.log('---tableContentDom--需要滚动条--');
          // 需要滚动条,所以需要设置Scrolly
          setScrollY(tableWrapperHeight - otherH); //ant-table-tbody的最大高度
        }
      } else if (tbodyDom) {
        if (tbodyDom.style.maxHeight) {
          tbodyDom.style.removeProperty('max-height'); //为了兼容queryFilter--onCollapse
        }
        // 也需要判断是否需要滚动条
        const tbodyHeight = tbodyDom.offsetHeight; //offsetHeight:包含滚动条的
        if (tbodyHeight && tableWrapperHeight - otherH > tbodyHeight) {
          // console.log('---tbodyDom--不需要滚动条--')
          setScrollY(undefined);
        } else {
          // console.log('---tbodyDom--tbodyHeight--需要滚动条--:',tbodyHeight);
          // tbodyDom.style.height = tableWrapperHeight - otherH + 'px';
          tbodyDom.style.maxHeight = tableWrapperHeight - otherH + 'px'; // 不就是scrollY
          setScrollY(tableWrapperHeight - otherH);
        }
      }
    } else {
      setScrollY(undefined);
    }
  }, [
    firstChild,
    tableWrapperHeight,
    dataSourceLenght,
    filterHeight,
    tableExpendKeys,
  ]);

  const {
    cx,
    styles: { rewrite },
  } = useStyle();

  return {
    tableRef,
    scrollY,
    cx: cx.bind(null, rewrite),
  };
}
